﻿using AdminBase.Common.Helpers;
using AdminBase.Interface;
using AdminBase.Model;
using AdminBase.Model.Entitys;
using AutoMapper;
using SqlSugar;

namespace AdminBase.Service
{
    /// <summary>
    /// 角色业务实现类
    /// </summary>
    public class RolesService : IRolesService
    {
        private readonly IMapper _mapper;
        private ISqlSugarClient _db { get; set; }

        /// <summary>
        /// 构造注入
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="db"></param>
        public RolesService(IMapper mapper, ISqlSugarClient db)
        {
            _mapper = mapper;
            _db = db;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public bool Add(Roles entity)
        {
            entity.IsEnable = true;
            entity = EntityHelper.SetAddValues(entity);
            return _db.Insertable(entity).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public bool Edit(Roles entity)
        {
            var oEntity = _db.Queryable<Roles>().First(p => p.ID == entity.ID);
            oEntity = _mapper.Map(entity, oEntity);
            oEntity = EntityHelper.SetEditValues(oEntity);
            return _db.Updateable(oEntity).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Del(long id)
        {
            List<long> ids = new List<long>() { id };
            return DeleteRolesUsersPermissions(ids);
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        public bool BatchDel(List<long> idList)
        {
            if (idList.Any())
            {
                return DeleteRolesUsersPermissions(idList);
            }
            return false;
        }

        /// <summary>
        /// 删除关联数据
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        private bool DeleteRolesUsersPermissions(List<long> ids)
        {
            try
            {
                // 开始事务
                _db.Ado.BeginTran();

                // 删除角色
                _db.Deleteable<Roles>().In(ids).ExecuteCommand();
                // 删除角色权限
                _db.Deleteable<RolesPermissions>()
                    .Where(d => ids.Contains(d.RoleID))
                    .ExecuteCommand();
                // 删除用户角色
                _db.Deleteable<UsersRoles>()
                    .Where(d => ids.Contains(d.RoleID))
                    .ExecuteCommand();

                // 提交事务
                _db.Ado.CommitTran();
                return true;
            }
            catch (Exception ex)
            {
                // 回滚事务
                _db.Ado.RollbackTran();
                throw new ArgumentException($"执行删除角色事务时发生异常：{ex}");
            }
        }

        /// <summary>
        /// 根据ID获取角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Roles GetRoleById(long id)
        {
            return _db.Queryable<Roles>().First(p => p.ID == id);
        }

        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="queryParam">查询参数</param>
        /// <param name="pageBase">分页查询</param>
        /// <returns></returns>
        public PageInfo GetRoles(RolesQueryParam queryParam, PageBase pageBase)
        {
            var exp = _db.Queryable<Roles>();
            // 关键字
            if (!string.IsNullOrWhiteSpace(queryParam.KeyWord))
            {
                exp = exp.Where(p => p.Name.Contains(queryParam.KeyWord) || p.Description.Contains(queryParam.KeyWord));
            }
            // 是否启用
            if (queryParam.IsEnable.HasValue)
            {
                exp = exp.Where(p => p.IsEnable == queryParam.IsEnable.Value);
            }
            // 排序分页
            PageInfo pageInfo = PagedHelper.GetPageData(exp, pageBase);
            var list = pageInfo.Data as List<Roles>;
            var rolesDtos = _mapper.Map<List<RolesDto>>(list);
            // 获取权限
            var ids = rolesDtos.Select(p => p.ID).ToList();
            var rolePermissions = _db.Queryable<RolesPermissions>()
                .Where(p => ids.Contains(p.RoleID)).ToList();
            rolesDtos.ForEach(p =>
            p.Permissions.AddRange(
                rolePermissions.Where(r => r.RoleID == p.ID).Select(r => r.PermissionID)
                )
            );

            pageInfo.Data = rolesDtos;
            return pageInfo;
        }

        /// <summary>
        /// 获取全部角色用于下拉框
        /// </summary>
        /// <returns></returns>
        public List<RolesOptionDto> GetRolesOption()
        {
            var data = _db.Queryable<Roles>()
                .Where(p => p.IsEnable == true)
                .OrderBy(p => p.Name)
                .Select(p =>
                new RolesOptionDto()
                {
                    ID = p.ID,
                    Name = p.Name
                }).ToList();
            return data;
        }

        /// <summary>
        /// 设置权限
        /// </summary>
        /// <returns></returns>
        public bool SetPermissions(RolesDto rolesDto)
        {
            List<RolesPermissions> list = new List<RolesPermissions>();
            rolesDto.Permissions.ForEach(p =>
            list.Add(
            new RolesPermissions()
            {
                RoleID = rolesDto.ID,
                PermissionID = p
            }));
            // 删除之前的权限
            _db.Deleteable<RolesPermissions>().Where(r => r.RoleID == rolesDto.ID).ExecuteCommand();
            return _db.Insertable(list).ExecuteCommand() > 0;
        }
    }
}
